package hash_table;

import java.util.LinkedList;

/**
 * @author 老顾
 * @title: HashMap02BySeparateChaining
 * @projectName java-restudy
 * @description 拉链法
 * @email: 1437594522@qq.com
 * @date 2022/11/7 14:44
 */
public class HashMap02BySeparateChaining<K, V> implements Map<K, V> {

    private final LinkedList<Node<K, V>>[] tab = new LinkedList[8];

    @Override
    public void put(K key, V value) {
        int index = key.hashCode() & (tab.length - 1);
        if (tab[index] == null) {
            tab[index] = new LinkedList<>();
            tab[index].add(new Node<>(key, value));
        }else {
            tab[index].add(new Node<>(key, value));
        }
    }

    @Override
    public V get(K key) {
        int index = key.hashCode() & (tab.length - 1);
        for (Node<K, V> kvNode : tab[index]){
            if (key.equals(kvNode.getKey())){
                return kvNode.value;
            }
        }
        return null;
    }

    static class Node<K, V> {
        final K key;
        V value;

        Node(K key,V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }
    }
}
